package com.starleague.entity.android;

import java.util.Observable;
import java.util.Observer;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.LinearLayout;

import com.starleague.common.IObservable;
import com.starleague.entity.IEntity;

public abstract class AbstractEntityView
        extends LinearLayout
        implements Observer
{
    private IEntity entity;
    private Runnable updateRunnable;

    public AbstractEntityView(Context context,
                              AttributeSet attrs)
    {
        super(context, attrs);
        init(context, attrs);
    }

    public AbstractEntityView(Context context,
                              AttributeSet attrs,
                              int defStyle)
    {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    public IEntity getEntity()
    {
        return this.entity;
    }

    public void setEntity(IEntity entity)
    {
        this.entity = entity;
    }

    protected abstract void doUpdate();

    @Override
    protected void onAttachedToWindow()
    {
        super.onAttachedToWindow();

        doUpdate();

        if (this.entity instanceof IObservable)
            ((IObservable) this.entity).addObserver(this);
    }

    @Override
    protected void onDetachedFromWindow()
    {
        if (this.entity instanceof IObservable)
            ((IObservable) this.entity).deleteObserver(this);

        super.onDetachedFromWindow();
    }

    @Override
    public final void update(Observable observable,
                             Object data)
    {
        this.post(this.updateRunnable);
    }

    private void init(Context context,
                      AttributeSet attrs)
    {
        this.updateRunnable = new Runnable()
        {
            @Override
            public void run()
            {
                AbstractEntityView.this.doUpdate();
            }
        };
    }
}
